package com.shen.service;

import com.alibaba.fastjson.JSON;
import com.shen.pojo.Content;
import com.shen.util.HtmlParseUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.swing.text.Highlighter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

//业务编写
@Service
public class ContentService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    //把解析的数据添加到es中
    public  Boolean parseContent(String keywords) throws IOException {
        //查询关键词
        List<Content> contents=new HtmlParseUtil().parseJD(keywords);
        //将查询的数据放到es中去
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");

        //查询es是否存在jd_goods
        if(isExistIndex("jd_goods")==false){
            createIndex("jd_goods"); //没有就创建一个
        }

        for (int i = 0; i < contents.size(); i++) {
            bulkRequest.add(new IndexRequest("jd_goods").source(JSON.toJSONString(contents.get(i)), XContentType.JSON));
        }

        //执行
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);

        return !bulk.hasFailures();
    }


    /**
     * 索引查询
     */
    public boolean isExistIndex(String index) throws IOException {
        if(restHighLevelClient.indices().exists(new GetIndexRequest(index), RequestOptions.DEFAULT)){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 索引创建
     */

    public void createIndex(String index) throws IOException {
        restHighLevelClient.indices().create( new CreateIndexRequest(index),RequestOptions.DEFAULT);
    }

    /**
     * 分页查询
     * @param keyword
     * @param pageNo
     * @param pageSize
     * @return
     * @throws IOException
     */
    public List<Map<String,Object>> searchPage(String keyword, int pageNo, int pageSize) throws IOException {
        if(pageNo<=1){
            pageNo=1;
        }
        //条件搜索
        SearchRequest request=new SearchRequest("jd_goods");
        SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();

        //分页
        searchSourceBuilder.from(pageNo);
        searchSourceBuilder.size(pageSize);

        //精准匹配
        TermQueryBuilder termQueryBuilder= QueryBuilders.termQuery("title",keyword);
        searchSourceBuilder.query(termQueryBuilder);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //高亮
        HighlightBuilder highlighter = new HighlightBuilder();
        highlighter.field("title");
        highlighter.requireFieldMatch(false);//是否高亮所有关键词
        highlighter.preTags("<span style='color:red'>");
        highlighter.postTags("</span>");
        searchSourceBuilder.highlighter(highlighter);

        //执行搜索
        request.source(searchSourceBuilder);
        SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);


        List<Map<String,Object>> list=new ArrayList<>();
        //解析结果
        for (SearchHit fields : search.getHits().getHits()) {
            //获得高亮的字段
            Map<String, HighlightField> highlightFields = fields.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            //替换成高亮的字段
            Map<String, Object> sourceAsMap = fields.getSourceAsMap();//没有高亮的字段
            if(title!=null){
                Text[] fragments = title.fragments();
                String text="";
                for (Text fragment : fragments) {
                    text+=fragment;
                }
                sourceAsMap.put("title",text);  //替换成高亮的字段
            }
            list.add(fields.getSourceAsMap());
        }

        return list;
    }
}
